package com.ewanghuiju.app.base;

import java.util.ArrayList;
import java.util.List;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

/**
 * @author sj  qq:751943509
 * @class tab切换的公共activity
 * @time 2020/2/17
 */
public abstract class BaseFragmentActivity extends SimpleActivity {

    protected FragmentManager fm = getSupportFragmentManager();

    public FragmentTransaction getFragmentTransaction() {

        FragmentTransaction transaction = fm.beginTransaction();

        return transaction;
    }

    private List<Fragment> listFragment = new ArrayList<>();

    public void addFragment(Fragment fragment) {
        if (!listFragment.contains(fragment)) {
            listFragment.add(fragment);
        }
    }

    public boolean getFragment(Fragment fragment) {
        boolean isExist = listFragment.contains(fragment);
        addFragment(fragment);
        return isExist;
    }

    public void showFragmentF(Fragment fragment) {
        showFragmentF(fragment, "");

    }

    public void showFragmentF(Fragment fragment, String extra) {

        FragmentTransaction transaction = getFragmentTransaction();

        if (getFragment(fragment)) {
            transaction.show(fragment);
        } else {
            if (!isAdded(fragment)) {
                transaction.add(getFrameLayoutId(), fragment, extra + fragment.getClass().getName());
            } else {
                hideFragmentF();
                transaction.show(fragment);
            }


        }
        transaction.commitAllowingStateLoss();
    }

    public boolean isAdded(Fragment fragment) {
        if (fm.findFragmentByTag(fragment.getClass().getName()) != null) {
            return true;
        }
        ;
        return false;
    }

    public int getFrameLayoutId() {
        return 0;
    }

    public void hideFragmentF() {
        FragmentTransaction transaction = getFragmentTransaction();
        for (int i = 0; i < listFragment.size(); i++) {

            if (listFragment.get(i) != null) {

                transaction.hide(listFragment.get(i));
            }
        }
        transaction.commitAllowingStateLoss();
    }
}
